$NG.AllReady(function (page, { useValuesChange,useDataIndexChange,useUpdateRows,useUpdateRow,useBeforeClick }) {
    //获取控件,
    var mstfrom = $NG.getCmpApi("p_form_tenancy_change_m");
    var grid = $NG.getCmpApi("p_form_tenancy_change_d");
    if(page.oType =='add'){
        $NG.updateState((updater)=>{
            updater.data.p_form_tenancy_change_m.setProps({
                bill_name:'租房申请变更',
                u_ywlx:'租凭费'
            })
        })
    }
    useValuesChange(({args})=>{
        const _data = args[0]
        console.log(`项目监听`,_data);
        getProjectInfo()
        ZfMFilter()
    },"p_form_tenancy_change_m.phid_pc")
    getProjectInfo();
    useValuesChange(({args})=>{
        sDtToeDt(mstfrom.getItem("u_ex_start_dt").getValue(),mstfrom.getItem("u_ex_end_dt").getValue())
    },"p_form_tenancy_change_m.u_ex_start_dt")
    useValuesChange(({args})=>{
        sDtToeDt(mstfrom.getItem("u_ex_start_dt").getValue(),mstfrom.getItem("u_ex_end_dt").getValue())
    },"p_form_tenancy_change_m.u_ex_end_dt")
        //计算申请月数
        function sDtToeDt(date1, date2) {
			const st = new Date(date1);
			const et = new Date(date2);
			const day = et - st;
			console.log("day", day);
			window.monthNum = (
				Number(Math.ceil((et - st) / (1000 * 60 * 60 * 24)) / 30) || 0
			).toFixed(2);
		}
	// 获取项目
	function getProjectInfo(phid=mstfrom.getItem("phid_pc").getValue(),lock = false) {
		if (!phid) return;
		$NG.execServer("getPtInfoByPhid", {phid}, (res) => {
			const _data = JSON.parse(res.data)[0].extendObjects;
			console.log(`获取项目信息`, _data);
			$NG.updateState((updater) => {
				updater.data.p_form_tenancy_change_m.setProps({
					u_pc_no: _data.pc_no, //项目编码    
					u_fycdgs: {
						//事业部or组织
						value: _data.org_phid,
						label: _data.org_name,
					},
                    u_account_company: {
						//事业部or组织
						value: _data.org_phid,
						label: _data.org_name,
					},
					u_regional_center: {
						//区域中心
						value: _data.regional_center_phid,
						label: _data.regional_center_name,
					},
					u_fycd_dept: {
						//部门
						value: _data.dept_phid,
						label: _data.dept_name,
					},
                    u_project_manager:{
                        label:_data.project_manager_name,
                        value:_data.project_manager_phid
                    },
                    
				});
			});
            if(lock){
                return _data
            }
		});
	}

    window.__cache_lsz_count_per = 0
    useUpdateRows(({args})=>{
        const arr = args[0]
        // 计算总价
        // arr.forEach(item=>{
        //     item.u_total = (Number(item.u_rent_prc)||0)*(Number(item.u_month)||0)+(Number(item.u_taxe_amt)||0)+(Number(item.u_zj_amt)||0)
        // })
        // 汇总总价，如果总价无变化则不更改节省性能
        console.log(`触发`,arr);
        let _count_per = 0
        arr.forEach(item=>{
            if(!item.u_taxrate){
                item.u_taxrate=0
            }
            item.u_xmonth = window.monthNum
            _count_per+=(Number(item.u_sjrzrs) || 0)
        })
        // if(window.__cache_lsz_count_per!=_count_per){
        //     window.__cache_lsz_count_per = _count_per
        //     $NG.updateState((updater)=>{
        //         updater.data.p_form_tenancy_change_m.setProps({
        //             u_rz_qyt:_count_per
        //         })
        //     })
        // }
        let _count_total_amt = args[0].reduce((value,item)=>{
            return value+(Number(item.u_total_amt))
        },0)
        console.log(`总金额`,_count_total_amt);
        $NG.updateState((updater)=>{
                updater.data.p_form_tenancy_change_m.setProps({
                    u_sq_amt:_count_total_amt
                })
        })
        grid.refreshView()
    },"p_form_tenancy_change_d")

    useValuesChange(({args})=>{
        getZfsqRoi()
    },"p_form_tenancy_change_m.u_tenancy")

    amtReduce(["u_rent_amt_vat","u_month","u_rent_amt","u_rent_amt_vat","amt","u_taxrate","u_taxe_amt","u_zj_amt","u_rent_prc_vat"])
    function amtReduce(arr){
        arr.forEach(item=>{
            useDataIndexChange(({args})=>{
                amtReduce_d(args)
            },item)
        })
    }
    function amtReduce_d(args){
        const row = args[0];
		//房租含税
		row.u_rent_amt_vat = (Number(row.u_rent_prc_vat) || 0) * (Number(row.u_xmonth) || 0);
		//房租未税
		row.u_rent_amt = (Number(row.u_rent_amt_vat) || 0) / (1 + Number(row.u_taxrate));
		//税额u_taxe_amt
		row.u_taxe_amt = Number(row.u_rent_amt_vat) - Number(row.u_rent_amt);
        //重新计算总额
		args[0].u_total_amt = (Number(args[0].u_rent_amt_vat)||0)+(Number(args[0].u_zj_amt)||0)
        const arr =grid.getRows()
        let _count_total_amt = arr.reduce((value,item)=>{
            return value+(Number(item.u_total_amt))
        },0)
        console.log(`总金额`,_count_total_amt);
        $NG.updateState((updater)=>{
            updater.data.p_form_tenancy_change_m.setProps({
                u_sq_amt:_count_total_amt
            })
        })
		grid.refreshView();
    }


    zhufangbiaozhun(["u_city","u_floor"])
    function zhufangbiaozhun(arr){
        arr.forEach(item=>{
            useDataIndexChange(({args})=>{
                const city_phid = args[0].u_city
                const ceng = args[0].u_floor
                if(city_phid&&ceng){
                    $NG.execServer('getRentalStandardsByCity',{city_phid}, function(res){
                        console.log(`住房`,res, city_phid, ceng);
                        if(res.count == 0) return
                        const _data = JSON.parse(res.data)[0].extendObjects
                        if(ceng == '1'){
                            args[0].u_bzbz = _data.u_gcwybz
                        } else {
                            args[0].u_bzbz = _data.u_dcwybz
                        }
                        args[0].u_zfbz = _data.u_bz
                        args[0].u_city_type=_data.u_cslb
                        grid.refreshView()
                    })
                }
                
            },item)
        })
    }

    //获取原信息
    function getZfsqRoi(){
        $NG.execServer("getZfsqRoi", {phid:mstfrom.getItem("u_tenancy").getValue()}, function (res){
            console.log(res);
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater)=>{
                updater.data.p_form_tenancy_change_m.setProps({
                    u_tenancy_no:_data.bill_no,
                    u_ex_start_dt_ori:_data.bill_dt,
                    u_ex_end_dt_ori:_data.u_end_dt,
                    u_sq_amt_ori:_data.u_sq_amt
                })
            })
        })
    }
    //判断预期日期是否合理
    // 传入开始时间和结束时间字符串，传入一个回调函数用来清空时间字段：()=>{ 清空逻辑 }
    //示例
    useValuesChange(({args})=>{
        isDate(mstfrom.getItem("bill_dt").getValue(), mstfrom.getItem("u_end_dt").getValue(), ()=>{
            $NG.updateState((updater)=>{
                updater.data.p_form_tenancy_m.setProps({
                    u_end_dt:null
                })
            })
        })
    },"p_form_tenancy_change_m.u_ex_end_dt")
    function isDate(startDate, endDate, fun){
        try{
            const sDate = new Date(startDate).getTime()
            const eDate = new Date(endDate).getTime()
            let time = eDate-sDate
            if(time<0){
                if(!fun){
                    $NG.alert("报错函数：isDate，没有传入回调函数！")
                }else{
                    $NG.alert("预计结束时间不得小于申请时间")
                    fun()
                }
            }
        }catch(err){
            $NG.alert("报错函数：isDate，传入的字符串不合法")
        }
    }


    // 过滤
    ZfMFilter()
function ZfMFilter() {
    $NG.updateUI((updater, state) => {
        console.log('过滤参数检查', updater);
        updater.fieldSetForm.p_form_tenancy_change_m.u_tenancy.setProps({
            onBeforeOpen: async () => {
                var phid_pc = $NG.getCmpApi('p_form_tenancy_change_m').getItem('phid_pc').getValue();
                if (!phid_pc) {
                    $NG.alert("请先选择项目");
                    return false;
                } else {
                    return true;
                }
            },
            ...(!!$NG.getCmpApi('p_form_tenancy_change_m').getItem('phid_pc').getValue() && {
                clientSqlFilter: {
                    phid_pc: $NG.getCmpApi('p_form_tenancy_change_m').getItem('phid_pc').getValue()
                }
            }),
        });
    });
}




    // 根据费用编码带出费用名称
    function getFynameByFyno(phid,fun){
        $NG.execServer("getFynameByFyno", {phid},function(res){
            console.log(res);
            if(res.count ==0||!phid)return 
            const _data = JSON.parse(res.data)[0].extendObjects
            fun(_data)
        })
    }
    //时间计算(月份)
    function sumDate(start,end){
        const staDt = new Date(start).getTime()
        const endDt = new Date(end).getTime()
        const sum = endDt-staDt
        const month = Number(Number(sum)/1000/60/60/24/30).toFixed(2)
        return month
    }
    useBeforeClick(function ({ args }) {
        //按钮点击前事件
        console.log("save按钮点击");
        const _arrs = grid.getRows()
        console.log(_arrs)
        let _cache_index = _arrs.reduce((value,item,index)=>{
            if(Number(item.u_rent_prc>(Number(item.u_sjrzrs)||0)*(Number(item.u_zfbz)||0))){
                value.push(index+1)
            }
                return value
        },[])
        if(_cache_index.length>0){
            $NG.alert(`表体明细中第 ${_cache_index.join("、")} 行中，月租含税金额超出->人数*租房标准，不符合规范，请修改!!`)
            return false
        }else {return true}
    }, "save");
});

